package com.wangxiaobao.charge.scsi;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.*;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.wangxiaobao.charge.mylibrary.engine.Scsi;
import com.wangxiaobao.charge.mylibrary.utils.ByteUtil;
import com.wangxiaobao.charge.mylibrary.utils.LogUtil;
import com.wangxiaobao.charge.mylibrary.utils.StringUtil;
import me.jahnen.libaums.core.UsbMassStorageDevice;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity implements View.OnClickListener {
    private Context mContext;
    private UsbManager mUsbManager;
    private PendingIntent mPermissionIntent;
    private Scsi scsi;
    private static final String ACTION_USB_PERMISSION = "com.demo.otgusb.USB_PERMISSION";

    private TextView snTv,timeTv,rkTv,espTv,macTv,currentWifiTv,testMicTv,testLightTv,deviceModelTv;

    @Override
    protected void onDestroy() {
        unregisterReceiver(mUsbReceiver);
        super.onDestroy();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        setContentView(R.layout.activity_main);



        logMessage("位:"+ ByteUtil.getHeight4((byte)16));
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        //注册广播,监听USB插入和拔出
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        intentFilter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, intentFilter);


        findViewById(R.id.snLayout).setOnClickListener(this);
        findViewById(R.id.timeLayout).setOnClickListener(this);
        findViewById(R.id.lightLayout).setOnClickListener(this);
        findViewById(R.id.rebootLayout).setOnClickListener(this);
        findViewById(R.id.resumeFactoryLayout).setOnClickListener(this);
        findViewById(R.id.wifiLayout).setOnClickListener(this);
        findViewById(R.id.wifiConnectLayout).setOnClickListener(this);
        findViewById(R.id.testMicLayout).setOnClickListener(this);
        findViewById(R.id.testLightLayout).setOnClickListener(this);
        findViewById(R.id.deviceModelLayout).setOnClickListener(this);


        snTv=findViewById(R.id.snTv);
        timeTv=findViewById(R.id.timeTv);
        rkTv=findViewById(R.id.rkTv);
        espTv=findViewById(R.id.espTv);
        macTv=findViewById(R.id.macTv);
        deviceModelTv=findViewById(R.id.deviceModelTv);
        currentWifiTv=findViewById(R.id.currentWifiTv);
        testMicTv=findViewById(R.id.testMicTv);
        testLightTv=findViewById(R.id.testLightTv);
        test();
    }
    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null)
                return;
            switch (action) {
                case ACTION_USB_PERMISSION://用户授权广播
                    synchronized (this) {
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //允许权限申请
                            test();
                        } else {
                            logMessage("用户未授权，访问USB设备失败");
                        }
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_ATTACHED://USB设备插入广播
                    logMessage("USB设备插入");
                    test();
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED://USB设备拔出广播
                    logMessage("USB设备拔出");
//                    if(scsi!=null)
//                        scsi.clear();
                    break;
            }
        }
    };

    public void test(){
        UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(MainActivity.this);
        for (UsbMassStorageDevice storageDevice : storageDevices){
            if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
                mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
                break;
            }
            UsbDevice usbDevice=storageDevice.getUsbDevice();
            logMessage("usbDevice:"+usbDevice.getSerialNumber());
            initCmd(storageDevice);
        }
    }


    public void logMessage(String value){
        LogUtil.log(value);
    }

    private void initCmd(UsbMassStorageDevice usbMassStorageDevice){
        if(usbMassStorageDevice==null){
            Toast.makeText(mContext,"没有USB设置挂载",Toast.LENGTH_LONG).show();
            return;
        }

        try {
            usbMassStorageDevice.init();
            scsi= new Scsi(usbMassStorageDevice.scsiBlockDevice);
        } catch (Exception e) {
            logMessage("异常:"+e.getMessage());
            e.printStackTrace();
        }


        String sn= "";
        try {
            sn = scsi.getSn();
        } catch (Exception e) {
            sn=e.getMessage();
        }
        snTv.setText(sn);

        String time= "";
        try {
            long timestamp = scsi.getTime();
            logMessage("时间戳:"+timestamp);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time=simpleDateFormat.format(new Date(timestamp*1000l));
        } catch (Exception e) {
            time=e.getMessage();
        }
        timeTv.setText(time);

        String rk= "";
        try {
            rk = scsi.getRK();
        } catch (Exception e) {
            rk=e.getMessage();
        }
        rkTv.setText(rk);

        String esp= "";
        try {
            esp = scsi.getESP();
        } catch (Exception e) {
            esp=e.getMessage();
        }
        espTv.setText(esp);

        String mac= "";
        try {
            mac = scsi.getMac();
        } catch (Exception e) {
            mac=e.getMessage();
        }
        macTv.setText(StringUtil.formatMac(mac,":").toUpperCase());

        String wifiName= "";
        try {
            wifiName = scsi.getWIFI();
        } catch (Exception e) {
            wifiName=e.getMessage();
        }
        currentWifiTv.setText(wifiName);

        String deviceModel= "";
        try {
            String model = scsi.getDeviceModel();
            deviceModel="1".equals(model)?"工厂模式":"用户模式";
        } catch (Exception e) {
            deviceModel=e.getMessage();
        }
        deviceModelTv.setText(deviceModel);
    }

    @Override
    public void onClick(View v) {
        if(scsi==null){
            Toast.makeText(mContext,"没有USB设置挂载",Toast.LENGTH_LONG).show();
            return;
        }
        switch (v.getId()){
            case R.id.snLayout:
                final EditText et = new EditText(this);
                et.setText("WXBY0302112040024");
                new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setView(et)
                        .setMessage("请输入sn号")
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                        .setPositiveButton("确定", (dialog, which) -> {
                            try {
                                String sn=et.getText().toString();
                                scsi.setSn(sn);
                                snTv.setText(sn);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(mContext,"同步时间失败:"+e.getMessage(),Toast.LENGTH_LONG).show();
                            }
                        })
                        .show();
                break;
            case R.id.timeLayout:
                new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage("是否同步时间?")
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                        .setPositiveButton("确定", (dialog, which) -> {
                            try {
                                long time=System.currentTimeMillis();
                                scsi.setTime(time);
                                timeTv.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time));
                            } catch (Exception e) {
                                e.printStackTrace();
                                timeTv.setText("设置时间失败:"+e.getMessage());
                            }
                        }).show();
                break;
            case R.id.lightLayout:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择指示灯操作类型")
                        .setItems(new String[]{ "关闭指示灯","打开指示灯"}, (dialogInterface, i) -> {
                            try {
                                scsi.setLight(i);
                            } catch (Exception e) {
                                Toast.makeText(mContext,"设置指示灯异常:"+e.getMessage(),Toast.LENGTH_LONG).show();
                                e.printStackTrace();
                            }
                        }).show();
                break;

            case R.id.deviceModelLayout:
                String[] itemx=new String[]{ "用户模式","工厂模式"};
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择设备模式")
                        .setItems(itemx, (dialogInterface, i) -> {
                            try {
                                scsi.setDeviceModel(i);
                                deviceModelTv.setText(itemx[i]);
                            } catch (Exception e) {
                                Toast.makeText(mContext,"设置设备模式异常:"+e.getMessage(),Toast.LENGTH_LONG).show();
                                e.printStackTrace();
                            }
                        }).show();
                break;
            case R.id.rebootLayout:
                new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage("是否重启设备?")
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                        .setPositiveButton("确定", (dialog, which) -> {
                            try {
                                scsi.reboot();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }).show();
                break;
            case R.id.resumeFactoryLayout:
                new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage("是否恢复出厂设置?")
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                        .setPositiveButton("确定", (dialog, which) -> {
                            try {
                                scsi.recovery();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }).show();
                break;
            case R.id.testMicLayout:
                Toast.makeText(mContext,"未实现",Toast.LENGTH_LONG).show();
                break;
            case R.id.testLightLayout:
                try {
                    scsi.testLight();
                } catch (Exception e) {
                    Toast.makeText(mContext,"指示灯测试异常:"+e.getMessage(),Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
                break;
            case R.id.wifiLayout:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择WIFI操作类型")
                        .setItems(new String[]{ "关闭WIFI","打开WIFI"}, (dialogInterface, i) -> {
                            try {
                                scsi.setWifiSwitch(i);
                            } catch (Exception e) {
                                Toast.makeText(mContext,"设置wifi开关异常:"+e.getMessage(),Toast.LENGTH_LONG).show();
                                e.printStackTrace();
                            }
                        }).show();
                break;
            case R.id.wifiConnectLayout:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择WIFI的操作类型")
                        .setItems(new String[]{ "连接WIFI","断开WIFI"}, (dialog, parentWhich) -> {
                            dialog.dismiss();
                            final ViewGroup viewGroup=(ViewGroup) getLayoutInflater().inflate(R.layout.wifi_layout,null,false);
                            EditText ssidEditTv=viewGroup.findViewById(R.id.ssidEditTv);
                            EditText passwordEditTv=viewGroup.findViewById(R.id.passwordEditTv);
                            new AlertDialog.Builder(mContext)
                                    .setTitle("提示")
                                    .setView(viewGroup)
                                    .setMessage("请输入WIFI信息")
                                    .setNegativeButton("取消", (dialog1, which) -> dialog1.dismiss())
                                    .setPositiveButton("确定", (dialog12, which) -> {
                                        String ssid=ssidEditTv.getText().toString();
                                        String password=passwordEditTv.getText().toString();
                                        if(TextUtils.isEmpty(ssid))
                                            return;
                                       if(parentWhich ==0){
                                           try {
                                               scsi.connectWifi(ssid,password);
                                               currentWifiTv.setText(ssid);
                                           } catch (Exception e) {
                                               Toast.makeText(mContext,"连接WIFI异常:"+e.getMessage(),Toast.LENGTH_LONG).show();
                                               e.printStackTrace();
                                           }
                                       }else{
                                           try {
                                               scsi.disconnectWifi(ssid);
                                               currentWifiTv.setText("");
                                           } catch (Exception e) {
                                               Toast.makeText(mContext,"断开WIFI异常:"+e.getMessage(),Toast.LENGTH_LONG).show();
                                               e.printStackTrace();
                                           }
                                       }
                                    })
                                    .show();
                        })
                        .show();
                break;
        }
    }
}
